﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// Hi-Pot管理窗体
    /// </summary>
    public partial class FormRJ6902 : HWFrmWithTitle
    {
        private bool mIsFirstTimeSelected = true;
        private int mTcpLastSelectedRowIndex = -1;
        private int mSerialLastSelectedRowIndex = -1;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormRJ6902()
        {
            InitializeComponent();
        }
        private void FormRJ6902_Load(object sender, EventArgs e)
        {
            InitRJ6902Columns();
            LoadRJ6902Config();
            this.labelStart.Select();
        }
        private void LoadRJ6902Config()
        {
            this.mIsFirstTimeSelected = true;
            this.mSerialLastSelectedRowIndex = -1;
            this.mTcpLastSelectedRowIndex = -1;
            this.dataGridViewSerial.Rows.Clear();
            this.dataGridViewTcp.Rows.Clear();
            this.dataGridViewModules.Rows.Clear();
            var deviceOtherConfig = BusinessConfig.Instance();
            this.textBoxTimeout.Text = deviceOtherConfig.RJ6902Timeout.ToString();
            this.textBoxDelayQueryTimes.Text = deviceOtherConfig.RJDelayQueryTimes.ToString();
            var tcpConfigs = RJ6902Helper.GetRJ6902TcpConfig();
            if (tcpConfigs != null && tcpConfigs.Count > 0)
            {
                foreach (var t in tcpConfigs)
                {
                    var index = this.dataGridViewTcp.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewTcp.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["TcpIP"].Value = t.ServerIP;
                    newRow.Cells["TcpPort"].Value = t.ServerPort.ToString();
                    newRow.Cells["MachineAddress"].Value = t.MachineAddress;
                    newRow.Tag = t;
                }
            }
            var comConfigs = RJ6902Helper.GetRJ6902ComConfig();
            if (comConfigs != null && comConfigs.Count > 0)
            {
                foreach (var t in comConfigs)
                {
                    var index = this.dataGridViewSerial.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewSerial.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["PortName"].Value = !string.IsNullOrWhiteSpace(t.PortName) && PortNames.Contains(t.PortName) ? t.PortName : PortNames[0];
                    newRow.Cells["Parity"].Value = t.Parity.ToString();
                    newRow.Cells["DataBit"].Value = t.DataBits.ToString();
                    newRow.Cells["StopBit"].Value = t.StopBits.ToString();
                    newRow.Cells["BaudRate"].Value = t.BaudRate.ToString();
                    newRow.Cells["MachineAddress"].Value = t.MachineAddress;
                    newRow.Tag = t;
                }
            }
            this.dataGridViewTcp.Rows[0].Cells[0].Selected = true;
        }
        private string[] PortNames = SerialPort.GetPortNames();
        DataGridViewComboBoxColumn portNameSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn baudRateSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn paritySerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataBitSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn stopBitSerialColumn = new DataGridViewComboBoxColumn();
        private void InitRJ6902Columns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpIP", "IP");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpPort", "端口");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "MachineAddress", "从机地址");
            this.dataGridViewTcp.DoubleBufferedDataGirdView(true);
            this.dataGridViewTcp.InitStyle();
            CommonHelper.InitComboGridColumn(portNameSerialColumn, "PortName", "串口", PortNames);
            CommonHelper.InitComboGridColumn(baudRateSerialColumn, "BaudRate", "波特率", new string[] { "2400", "4800", "9600", "14400", "19200", "115200" });
            CommonHelper.InitComboGridColumn(paritySerialColumn, "Parity", "校验位", new string[] { "0", "1", "2", "3", "4" });
            CommonHelper.InitComboGridColumn(dataBitSerialColumn, "DataBit", "数据位", new string[] { "5", "6", "7", "8" });
            CommonHelper.InitComboGridColumn(stopBitSerialColumn, "StopBit", "停止位", new string[] { "0", "1", "2", "3" });
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Name", "名称");
            this.dataGridViewSerial.Columns.Add(portNameSerialColumn);
            this.dataGridViewSerial.Columns.Add(baudRateSerialColumn);
            this.dataGridViewSerial.Columns.Add(paritySerialColumn);
            this.dataGridViewSerial.Columns.Add(dataBitSerialColumn);
            this.dataGridViewSerial.Columns.Add(stopBitSerialColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "MachineAddress", "从机地址");
            this.dataGridViewSerial.DoubleBufferedDataGirdView(true);
            this.dataGridViewSerial.InitStyle();
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Trigger", "触发地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Vd1", "Vd1");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Vd2", "Vd2");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Vd3", "Vd3");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Vp", "Vp");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Upt", "Upt");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Rtd", "Rtd");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "R1", "R1");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Oc", "Oc");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Sc", "Sc");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Uv", "Uv");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Ov", "Ov");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Drop1", "Drop1");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Drop2", "Drop2");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Drop3", "Drop3");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "TL", "TL");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "TH", "TH");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Rtr", "Rtr");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "R2", "R2");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Result", "Result");
            CommonHelper.CreateTextGridColumn(this.dataGridViewModules, "Done", "结果完成地址");
            this.dataGridViewModules.DoubleBufferedDataGirdView(true);
            this.dataGridViewModules.InitStyle();
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "数据保存中，请稍候......");
            if (GlobalStatus.APP == EAppStatus.RUN)
            {
                HWMessageBox.Show(this, "设备运行中，不允许修改参数");
                CommonHelper.CloseWaiting();
                return;
            }
            try
            {
                SaveModules();
                bool isValidTcp = true, isValidSerial = true, isValidOther = true;
                int timeout = 1000, delayQueryTimes = 300;
                List<RJ6902GXTCPParam> tcpList = new List<RJ6902GXTCPParam>();
                List<RJ6902GXComParam> comList = new List<RJ6902GXComParam>();
                if (this.dataGridViewTcp.Rows != null && this.dataGridViewTcp.Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataGridViewRow row in this.dataGridViewTcp.Rows)
                    {
                        var name = CommonHelper.GetCellStringValue(row, "Name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            RJ6902GXTCPParam p = row.Tag != null ? (RJ6902GXTCPParam)row.Tag : new RJ6902GXTCPParam();
                            if (tcpList.Find(v => v.Remark.Equals(name)) != null)
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                break;
                            }
                            var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                            var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                            var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                            IPAddress ipValue = null;
                            if (!IPAddress.TryParse(ip, out ipValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的IP有误");
                                isValidTcp = false;
                                break;
                            }
                            int portValue = 9004;
                            if (!int.TryParse(port, out portValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的端口有误");
                                isValidTcp = false;
                                break;
                            }
                            short machineAddressValue = 2;
                            if (string.IsNullOrWhiteSpace(machineAddress) || !short.TryParse(machineAddress, out machineAddressValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的从机地址有误");
                                isValidTcp = false;
                                break;
                            }
                            p.Remark = name;
                            p.ServerIP = ipValue.ToString();
                            p.ServerPort = portValue;
                            p.MachineAddress = machineAddressValue;

                            tcpList.Add(p);
                        }
                        rowIndex++;
                    }
                }
                if (isValidTcp)
                {
                    if (this.dataGridViewSerial.Rows != null && this.dataGridViewSerial.Rows.Count > 0)
                    {
                        int rowIndex = 0;
                        foreach (DataGridViewRow row in this.dataGridViewSerial.Rows)
                        {
                            RJ6902GXComParam p = row.Tag != null ? (RJ6902GXComParam)row.Tag : new RJ6902GXComParam();
                            var name = CommonHelper.GetCellStringValue(row, "Name");
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                if (comList.Find(v => v.Remark.Equals(name.ToString())) != null)
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                    break;
                                }
                                var portName = CommonHelper.GetCellStringValue(row, "PortName");
                                var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                                var parity = CommonHelper.GetCellStringValue(row, "Parity");
                                var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                                var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                                var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                                if (string.IsNullOrWhiteSpace(portName))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的串口有误");
                                    isValidSerial = false;
                                    break;
                                }
                                int baudRateValue = int.Parse(baudRate);
                                int parityValue = int.Parse(parity);
                                int dataBitValue = int.Parse(dataBit);
                                int stopBitValue = int.Parse(stopBit);
                                short machineAddressValue = 2;
                                if (string.IsNullOrWhiteSpace(machineAddress) || !short.TryParse(machineAddress, out machineAddressValue))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的从机地址有误");
                                    isValidSerial = false;
                                    break;
                                }
                                p.Remark = name;
                                p.MachineAddress = machineAddressValue;
                                p.BaudRate = baudRateValue;
                                p.Parity = parityValue;
                                p.DataBits = dataBitValue;
                                p.PortName = portName;
                                p.StopBits = stopBitValue;
                                comList.Add(p);
                            }
                            rowIndex++;
                        }
                    }
                }
                if (isValidTcp && isValidSerial)
                {
                    if (!int.TryParse(this.textBoxTimeout.Text, out timeout))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "超时时间或重复次数有误");
                    }
                    if (!int.TryParse(this.textBoxDelayQueryTimes.Text, out delayQueryTimes))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "延时查询时间有误");
                    }
                }
                if (isValidTcp && isValidSerial && isValidOther)
                {
                    RJ6902Helper.SaveRJ6902TcpConfig(tcpList);
                    RJ6902Helper.SaveRJ6902ComConfig(comList);
                    var otherConfig = BusinessConfig.Instance();
                    otherConfig.RJ6902Timeout = timeout;
                    otherConfig.RJDelayQueryTimes = delayQueryTimes;
                    otherConfig.Save();
                    LogHelper.Info($"修改RJ6902配置\r\n{CommonHelper.GetJsonString(otherConfig)}\r\n{CommonHelper.GetJsonString(tcpList)}\r\n{CommonHelper.GetJsonString(comList)}");
                    APPInstance.ResetHelpers();
                    this.DialogResult = DialogResult.OK;
                    HWMessageBox.Show(this, "保存成功");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
            }
            CommonHelper.CloseWaiting();
        }
        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var machineAddressCell = e.Row.Cells["MachineAddress"] as DataGridViewTextBoxCell;
            if (machineAddressCell != null)
            {
                machineAddressCell.Value = "2";
            }
        }
        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void dataGridViewSerial_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(portNameSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(paritySerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(baudRateSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(dataBitSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(stopBitSerialColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }
        private void dataGridViewSerial_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var portNameCell = e.Row.Cells["PortName"] as DataGridViewComboBoxCell;
            if (portNameCell != null && PortNames != null && PortNames.Length > 0)
            {
                portNameCell.Value = PortNames[0];
            }
            var baudRateCell = e.Row.Cells["BaudRate"] as DataGridViewComboBoxCell;
            if (baudRateCell != null)
            {
                baudRateCell.Value = "9600";
            }
            var parityCell = e.Row.Cells["Parity"] as DataGridViewComboBoxCell;
            if (parityCell != null)
            {
                parityCell.Value = "0";
            }
            var stopBitCell = e.Row.Cells["StopBit"] as DataGridViewComboBoxCell;
            if (stopBitCell != null)
            {
                stopBitCell.Value = "1";
            }
            var dataBitCell = e.Row.Cells["DataBit"] as DataGridViewComboBoxCell;
            if (dataBitCell != null)
            {
                dataBitCell.Value = "8";
            }
            var machineAddressCell = e.Row.Cells["MachineAddress"] as DataGridViewTextBoxCell;
            if (machineAddressCell != null)
            {
                machineAddressCell.Value = "2";
            }
        }
        private void toolStripMenuItemRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewTcp.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewTcp.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                    IPAddress ipValue = null;
                    if (!IPAddress.TryParse(ip, out ipValue))
                    {
                        HWMessageBox.Show(this, $"IP有误");
                    }
                    else
                    {
                        int portValue = 502;
                        if (!int.TryParse(port, out portValue))
                        {
                            HWMessageBox.Show(this, $"端口有误");
                        }
                        else
                        {
                            short machineAddressValue = 2;
                            if (!short.TryParse(machineAddress, out machineAddressValue))
                            {
                                HWMessageBox.Show(this, $"从机地址有误");
                            }
                            else
                            {
                                var helper = APPInstance.HELPERS != null ?
                                    APPInstance.HELPERS.Find(v => v is RJ6902Helper && v.Name.Equals(name)
                                    && v.CommunicationType == ECommunicationType.TCP && v.IsConnected) : null;
                                if (helper != null)
                                {
                                    try
                                    {
                                        string content = CommonHelper.RemoveEnterString((helper as RJ6902Helper).GetStartTest());
                                        HWMessageBox.Show(this, $"结果：{content}");
                                    }
                                    catch (Exception ex)
                                    {
                                        HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                    }
                                }
                                else
                                {
                                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                    try
                                    {
                                        byte[] cmd = RJ6902Helper.GetStartTestCommand((byte)machineAddressValue);
                                        socket.ReceiveTimeout = 1000;
                                        socket.ConnectAsync(ipValue, portValue).Wait(500);
                                        if (socket.Connected)
                                        {
                                            socket.Send(cmd);
                                            byte[] buffer = new byte[1024];
                                            int length = socket.Receive(buffer);
                                            if (length > 0)
                                            {
                                                string content = string.Join(" ", buffer.Take(length).Select(v => v.ToString("X2")));
                                                HWMessageBox.Show(this, $"结果：{content}");
                                            }
                                            else
                                            {
                                                HWMessageBox.Show(this, "通讯异常");
                                            }
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "无法建立连接");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                    }
                                    finally
                                    {
                                        if (socket != null && socket.Connected)
                                        {
                                            socket.Close();
                                            socket = null;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }
        private void toolStripMenuItemSerialRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewSerial.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewSerial.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                    if (string.IsNullOrWhiteSpace(portName))
                    {
                        HWMessageBox.Show(this, $"串口有误");
                    }
                    else
                    {
                        int baudRateValue = int.Parse(baudRate);
                        int parityValue = int.Parse(parity);
                        int dataBitValue = int.Parse(dataBit);
                        int stopBitValue = int.Parse(stopBit);
                        short machineAddressValue = 2;
                        if (!short.TryParse(machineAddress, out machineAddressValue))
                        {
                            HWMessageBox.Show(this, $"从机地址有误");
                        }
                        else
                        {
                            var helper = APPInstance.HELPERS != null ?
                                APPInstance.HELPERS.Find(v => v is RJ6902Helper
                                && v.Name.Equals(name)
                                && v.CommunicationType == ECommunicationType.SERIAL
                                && v.IsConnected) : null;
                            if (helper != null)
                            {
                                try
                                {
                                    string content = CommonHelper.RemoveEnterString((helper as RJ6902Helper).GetStartTest());
                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                            }
                            else
                            {
                                byte[] cmd = RJ6902Helper.GetStartTestCommand((byte)machineAddressValue);
                                SerialPort serialPort = new SerialPort(portName, baudRateValue,
                                    CommonHelper.GetEnumByRealValue(parityValue, Parity.None), dataBitValue,
                                    CommonHelper.GetEnumByRealValue(stopBitValue, StopBits.One));
                                try
                                {
                                    serialPort.Open();
                                    serialPort.Write(cmd, 0, cmd.Length);
                                    int length = 0;
                                    for (var i = 0; i < 3; i++)
                                    {
                                        System.Threading.Thread.Sleep(1);
                                        length = serialPort.BytesToRead;
                                        if (length > 0)
                                        {
                                            break;
                                        }
                                        System.Threading.Thread.Sleep(1000);
                                    }
                                    if (length > 0)
                                    {
                                        byte[] buffer = new byte[length];
                                        serialPort.Read(buffer, 0, length);
                                        string content = string.Join(" ", buffer.Take(length).Select(v => v.ToString("X2")));
                                        HWMessageBox.Show(this, $"结果：{content}");
                                    }
                                    else
                                    {
                                        HWMessageBox.Show(this, "通讯异常");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                                finally
                                {
                                    if (serialPort != null && serialPort.IsOpen)
                                    {
                                        serialPort.Close();
                                        serialPort = null;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }

        private void buttonMaxSize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }
        private void dataGridViewTcp_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();
                int selectedRowIndex = this.dataGridViewTcp.SelectedCells == null || this.dataGridViewTcp.SelectedCells.Count == 0 ? -1 : this.dataGridViewTcp.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewTcp.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                    IPAddress ipValue = null;
                    int portValue = 502;
                    short machineAddressValue = 2;
                    RJ6902GXTCPParam p = new RJ6902GXTCPParam()
                    {
                        Remark = name.ToString(),
                        ServerIP = IPAddress.TryParse(ip.ToString(), out ipValue) ? ipValue.ToString() : "",
                        ServerPort = int.TryParse(port.ToString(), out portValue) ? portValue : 0,
                        MachineAddress = short.TryParse(machineAddress.ToString(), out machineAddressValue) ? machineAddressValue : (short)2
                    };
                    if (row.Tag != null)
                    {
                        RJ6902GXTCPParam cp = row.Tag as RJ6902GXTCPParam;
                        p.AddressParameters = cp.AddressParameters;
                    }
                    row.Tag = p;
                    this.groupBoxModules.Text = $"【TCP】{name} -> 模组设定";
                    ShowModules(p.AddressParameters);
                    this.mSerialLastSelectedRowIndex = -1;
                    this.mTcpLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void SaveModules()
        {
            Console.WriteLine($"SaveModule, tcp：{this.mTcpLastSelectedRowIndex}，serial：{this.mSerialLastSelectedRowIndex}");
            List<BaseRJ6902GXParam> list = new List<BaseRJ6902GXParam>();
            if (this.dataGridViewModules.Rows != null && this.dataGridViewModules.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dataGridViewModules.Rows)
                {
                    var p = new BaseRJ6902GXParam()
                    {
                        TriggerAddress = CommonHelper.GetCellStringValue(row, "Trigger"),
                        Vd1Address = CommonHelper.GetCellStringValue(row, "Vd1"),
                        Vd2Address = CommonHelper.GetCellStringValue(row, "Vd2"),
                        Vd3Address = CommonHelper.GetCellStringValue(row, "Vd3"),
                        VpAddress = CommonHelper.GetCellStringValue(row, "Vp"),
                        UptAddress = CommonHelper.GetCellStringValue(row, "Upt"),
                        RtdAddress = CommonHelper.GetCellStringValue(row, "Rtd"),
                        CapDataAddress = CommonHelper.GetCellStringValue(row, "R1"),
                        OcAddress = CommonHelper.GetCellStringValue(row, "Oc"),
                        ScAddress = CommonHelper.GetCellStringValue(row, "Sc"),
                        UvAddress = CommonHelper.GetCellStringValue(row, "Uv"),
                        OvAddress = CommonHelper.GetCellStringValue(row, "Ov"),
                        Drop1Address = CommonHelper.GetCellStringValue(row, "Drop1"),
                        Drop2Address = CommonHelper.GetCellStringValue(row, "Drop2"),
                        Drop3Address = CommonHelper.GetCellStringValue(row, "Drop3"),
                        TLAddress = CommonHelper.GetCellStringValue(row, "TL"),
                        THAddress = CommonHelper.GetCellStringValue(row, "TH"),
                        RtrAddress = CommonHelper.GetCellStringValue(row, "Rtr"),
                        CapResultAddress = CommonHelper.GetCellStringValue(row, "R2"),
                        ResultAddress = CommonHelper.GetCellStringValue(row, "Result"),
                        TestDoneAddress = CommonHelper.GetCellStringValue(row, "Done"),
                    };
                    if (!string.IsNullOrWhiteSpace(p.TriggerAddress) && !string.IsNullOrWhiteSpace(p.TestDoneAddress) && !string.IsNullOrWhiteSpace(p.ResultAddress))
                    {
                        list.Add(p);
                    }
                }
            }
            if (this.mTcpLastSelectedRowIndex != -1)
            {
                var tcpRow = this.dataGridViewTcp.Rows[this.mTcpLastSelectedRowIndex];
                if (tcpRow != null && tcpRow.Tag != null)
                {
                    RJ6902GXTCPParam t = tcpRow.Tag as RJ6902GXTCPParam;
                    t.AddressParameters = list;
                    tcpRow.Tag = t;
                }
            }
            else if (this.mSerialLastSelectedRowIndex != -1)
            {
                var serialRow = this.dataGridViewSerial.Rows[this.mSerialLastSelectedRowIndex];
                if (serialRow != null && serialRow.Tag != null)
                {
                    RJ6902GXComParam t = serialRow.Tag as RJ6902GXComParam;
                    t.AddressParameters = list;
                    serialRow.Tag = t;
                }
            }
        }
        private void dataGridViewSerial_SelectionChanged(object sender, EventArgs e)
        {
            if (!this.mIsFirstTimeSelected)
            {
                SaveModules();
                int selectedRowIndex = this.dataGridViewSerial.SelectedCells == null || this.dataGridViewSerial.SelectedCells.Count == 0 ? -1 : this.dataGridViewSerial.SelectedCells[0].RowIndex;
                if (selectedRowIndex != -1)
                {
                    DataGridViewRow row = this.dataGridViewSerial.Rows[selectedRowIndex];
                    var name = CommonHelper.GetCellStringValue(row, "Name");
                    var machineAddress = CommonHelper.GetCellStringValue(row, "MachineAddress");
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    short machineAddressValue = 2;
                    int baudRateValue = int.Parse(baudRate);
                    int parityValue = int.Parse(parity);
                    int dataBitValue = int.Parse(dataBit);
                    int stopBitValue = int.Parse(stopBit);
                    RJ6902GXComParam p = new RJ6902GXComParam()
                    {
                        Remark = name,
                        PortName = portName,
                        BaudRate = baudRateValue,
                        DataBits = dataBitValue,
                        Parity = parityValue,
                        StopBits = stopBitValue,
                        MachineAddress = short.TryParse(machineAddress, out machineAddressValue) ? machineAddressValue : (short)2
                    };
                    if (row.Tag != null)
                    {
                        RJ6902GXComParam cp = row.Tag as RJ6902GXComParam;
                        p.AddressParameters = cp.AddressParameters;
                    }
                    row.Tag = p;
                    this.groupBoxModules.Text = $"【串口】{name} -> 模组设定";
                    ShowModules(p.AddressParameters);
                    this.mTcpLastSelectedRowIndex = -1;
                    this.mSerialLastSelectedRowIndex = selectedRowIndex;
                }
            }
            this.mIsFirstTimeSelected = false;
        }
        private void ShowModules(List<BaseRJ6902GXParam> list)
        {
            this.dataGridViewModules.Rows.Clear();
            if (list != null && list.Count > 0)
            {
                foreach (var l in list)
                {
                    int index = this.dataGridViewModules.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewModules.Rows[index];
                    newRow.Cells["Trigger"].Value = l.TriggerAddress;
                    newRow.Cells["Vd1"].Value = l.Vd1Address;
                    newRow.Cells["Vd2"].Value = l.Vd2Address;
                    newRow.Cells["Vd3"].Value = l.Vd3Address;
                    newRow.Cells["Vp"].Value = l.VpAddress;
                    newRow.Cells["Upt"].Value = l.UptAddress;
                    newRow.Cells["Rtd"].Value = l.RtdAddress;
                    newRow.Cells["R1"].Value = l.CapDataAddress;
                    newRow.Cells["Oc"].Value = l.OcAddress;
                    newRow.Cells["Sc"].Value = l.ScAddress;
                    newRow.Cells["Uv"].Value = l.UvAddress;
                    newRow.Cells["Ov"].Value = l.OvAddress;
                    newRow.Cells["Drop1"].Value = l.Drop1Address;
                    newRow.Cells["Drop2"].Value = l.Drop2Address;
                    newRow.Cells["Drop3"].Value = l.Drop3Address;
                    newRow.Cells["TL"].Value = l.TLAddress;
                    newRow.Cells["TH"].Value = l.THAddress;
                    newRow.Cells["Rtr"].Value = l.RtrAddress;
                    newRow.Cells["R2"].Value = l.CapResultAddress;
                    newRow.Cells["Result"].Value = l.ResultAddress;
                    newRow.Cells["Done"].Value = l.TestDoneAddress;
                }
            }
        }
        private void FormRJ6902_Shown(object sender, EventArgs e)
        {
        }
        private void FormRJ6902_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
    }
}
